package com.hr.controller.common;

import com.hr.utils.AliyunOSSOperator;
import com.hr.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@RestController
@Slf4j
@AllArgsConstructor
@Tag(name = "上传文件")
public class UploadController {

    private final AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        log.info("上传文件{}",file);

        if (!file.isEmpty()) {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //将原始文件名的后缀取下来
            String endName = null;
            if (originalFilename != null) {
                endName = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            //拼接成新的文件名
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + endName;
            //返回前端需要的文件路径
            String url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
            return Result.success(url);
        }

        return Result.error("上传失败");

    }


}
